package controllers

import (
	"backend/constants/errorCode"
	"backend/constants/usertype"
	"backend/models"
	"backend/service/common"
	"backend/utils"
	"encoding/json"
	"github.com/beego/beego/v2/adapter/logs"
	"github.com/beego/beego/v2/core/validation"
	beego "github.com/beego/beego/v2/server/web"
)


type UserController struct {
	beego.Controller
}


// URLMapping ...
func (c *UserController) URLMapping() {
	c.Mapping("Login", c.Login)
	c.Mapping("QueryList",c.QueryList)
	c.Mapping("Change",c.Change)
	c.Mapping("Password",c.Password)
	c.Mapping("Delete",c.Delete)
	c.Mapping("Add",c.Add)
}


// Login
// @Title 登录接口
// @Description create WitLesson
// @Param	id		string 	true		"用户ID"
// @Param	password		string 	true		"密码"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /login [post]
func (c *UserController)Login(){
	var result interface{}
	valid := validation.Validation{}
	username := c.Ctx.Input.Query("username")
	password := c.Ctx.Input.Query("password")
	valid.Required(username, "username")
	valid.Required(password, "password")
	if valid.HasErrors() {
		// 如果有错误信息，证明验证没通过
		// 打印错误信息
		var msg string
		for _, err := range valid.Errors {
			msg = err.Key + err.Message
		}
		result = errorCode.ErrParam.SetMsg(msg)
	}else{
		password = utils.SHA256([]byte(password)) // 转换为hash256再进行登录
		isExist,member := models.IsCurrentUser(username,password)
		if isExist{
			data := models.GetUserData(member)
			token := utils.CreateRandStr(username,"")
			common.SaveToken(token,username)
			data["token"] = token
			result = errorCode.OK.WithData(data)
		}else{
			result = errorCode.ErrUserNotFound
		}
	}
	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}


// QueryList
// @Title 登录接口
// @Description create WitLesson
// @Param	page		int 	true		"页码"
// @Param	limit		int 	true		"每页数量"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /queryList [get]
func (c *UserController)QueryList(){
	var result interface{}
	page, _ := c.GetInt64("page", 1)
	limit, _ := c.GetInt64("limit", 10)
	count,list := models.GetUserList(page,limit)
	data := make(map[string]interface{})
	data["count"] = count
	data["list"] = list
	result = errorCode.OK.WithData(data)
	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}


// Change
// @Title Change
// @Description Change
// @Param	id		int 	true		"id"
// @Param	type		string 	true		"type"
// @Param	value		bool 	true		"value"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /change [post]
func (c *UserController)Change(){
	var result interface{}
	id, _ := c.GetInt64("id",0)
	accessType  := c.GetString("type")
	accessValue, _ := c.GetBool("value", false)
	if accessType == "list" ||accessType == "read" || accessType == "write" || accessType == "rename"|| accessType == "create"|| accessType == "copy"|| accessType == "remove"{
		if models.ChangeUserAccess(id,accessType,accessValue){
			data := make(map[string]interface{})
			data["id"] = id
			data["type"] = accessType
			data["value"] = accessValue
			result = errorCode.OK
		}else{
			result = errorCode.ErrServer.SetMsg("设置权限失败")
		}
	}else{
		result = errorCode.ErrParam
	}

	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}

// Delete
// @Title Delete
// @Description Delete
// @Param	id		int 	true		"id"
// @Param	type		string 	true		"type"
// @Param	value		bool 	true		"value"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /delete [post]
func (c *UserController)Delete(){
	var result interface{}
	username := common.GetUserId(c.Ctx)
	id, _ := c.GetInt64("id",0)
	if models.IsExistId(id){
		currentId := models.GetUserIdByUsername(username)
		if currentId == id{
			result = errorCode.ErrParam.SetMsg("不能删除自己")
		}else{
			if models.DeleteUser(id){
				result = errorCode.OK
			}else{
				result = errorCode.ErrParam.SetMsg("删除失败")
			}
		}
	}else{
		result = errorCode.ErrParam.SetMsg("该ID不存在")
	}

	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}


// Password
// @Title Password
// @Description Password
// @Param	id		int 	true		"id"
// @Param	type		string 	true		"type"
// @Param	value		bool 	true		"value"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /password [post]
func (c *UserController)Password(){
	var result interface{}
	id, _ := c.GetInt64("id",0)
	password := c.GetString("password")
	if password != ""{
		if models.IsExistId(id){
			password = utils.SHA256([]byte(password))
			if models.ChangeUserPassword(id,password){
				result = errorCode.OK
			}else{
				result = errorCode.ErrParam.SetMsg("修改密码失败")
			}
		}else{
			result = errorCode.ErrParam.SetMsg("该ID不存在")
		}
	}else{
		result = errorCode.ErrParam
	}

	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}


// Add
// @Title Add
// @Description Add
// @Param	id		int 	true		"id"
// @Param	type		string 	true		"type"
// @Param	value		bool 	true		"value"
// @Success 201 {int} models.WitLesson
// @Failure 403 body is empty
// @router /add [post]
func (c *UserController)Add(){
	var result interface{}
	username := c.GetString("username")
	password := c.GetString("password")
	userType := c.GetString("type")
	if password != ""{
		if !models.IsExistUsername(username){
			password = utils.SHA256([]byte(password))
			defaultAccess := make(map[string]interface{})
			defaultAccess["list"] = true
			defaultAccess["read"] = true
			defaultAccess["write"] = true
			defaultAccess["rename"] = true
			defaultAccess["copy"] = true
			defaultAccess["create"] = true
			defaultAccess["remove"] = true
			marshal, _ := json.Marshal(defaultAccess)
			access := string(marshal)
			if userType == usertype.ADMIN || userType == usertype.MANAGER|| userType == usertype.GUEST{
				if models.InsertUser(username,password,access,userType){
					result = errorCode.OK
				}else{
					result = errorCode.ErrParam.SetMsg("修改密码失败")
				}
			}else{
				result = errorCode.ErrParam.SetMsg("用户类型不符合规则")
			}

		}else{
			result = errorCode.ErrParam.SetMsg("用户名重复")
		}
	}else{
		result = errorCode.ErrParam
	}

	c.Data["json"] = result
	err := c.ServeJSON()
	if err != nil {
		logs.Error(err.Error())
		return
	}
}

